//
//  YWNoticeTableViewController.m
//  maintain
//
//  Created by 郑想 on 16/7/19.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import "UIScrollView+EmptyDataSet.h"
#import "YWNoticeTableViewController.h"
#import "YWMacro.h"
#import "UIColor+CustomColors.h"
#import "NSDate+YYAdd.h"
#import "YWattachment.h"
#import "YWNotifyManager.h"
#import "MJRefresh.h"
#import "YWNotice.h"
#import "YWNoticeManager.h"
#import "YWTempMission.h"
#import "YWCommonTool.h"
#import <QuickLook/QuickLook.h>
#import "YWResourceManager.h"
#import "YWPush.h"
//#import "YWNoReadReplyTableViewController.h"
//#import "YWReplyManager.h"
#import "YWDetailNoticeViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWNoticeAndTempMissionCell.h"
#import "YWNewNoticeTableViewController.h"
#import "YWEwinManager.h"

@interface YWNoticeTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (nonatomic, strong) NSMutableArray* dataSource;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) YWattachment *attachment;

@property (nonatomic, assign) NSInteger noticeStartId;
@property (nonatomic, assign) NSInteger tempMissionStartId;

@property (nonatomic, strong) NSMutableArray *menuNameArray;
@end

@implementation YWNoticeTableViewController

//-(instancetype)initWithStyle:(UITableViewStyle)style{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"notice", nil);//@"通知";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.page = 1;
    
    if (self.menuNameArray.count>0) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(clickRightBarButtonEvent:)];
    }
    
    [self setUpNotifications];
    
    [self setupTableView];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWNoticeAndTempMissionCell class] forCellReuseIdentifier:YWNoticeAndTempMissionCellIdentifier];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - datasource
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        [_dataSource addObjectsFromArray:[[YWNoticeManager shareManager]noticesOfTypeWithMeOrOthers:YWNoticeTypeOfAll page:self.page]];
    }
    return _dataSource;
}

- (NSMutableArray *)menuNameArray{
    if (!_menuNameArray) {
        _menuNameArray = [[NSMutableArray alloc] initWithArray:[[YWEwinManager shareManager] ewinMenuWithMenuEnName:ewinMenuEnName_notice]];
    }
    return _menuNameArray;
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource[section] count];
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWNoticeAndTempMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoticeAndTempMissionCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
//}

- (void)configureCell:(YWNoticeAndTempMissionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWNotice *notice = self.dataSource[indexPath.section][indexPath.row];
    cell.showExpendBtn = YES;
    //通知中不显示 请于...完成
    [cell viewWithTag:101].hidden = YES;
    //cell.delegate = self;
    cell.notice = notice;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YWNoticeAndTempMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNoticeAndTempMissionCellIdentifier];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWNotice *notice = self.dataSource[indexPath.section][indexPath.row];
    YWDetailNoticeViewController *noticeDetailVC = [YWDetailNoticeViewController new];
    noticeDetailVC.notice = notice;
    [self.navigationController pushViewController:noticeDetailVC animated:YES];
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWNoticeTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *temp = self.dataSource[section];
    YWNotice* notice = temp.count ? temp[0] : nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:notice.createTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:notice.createTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

#pragma mark - refresh method
- (void)refreshTop
{
    self.page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    if (refreshType == YWTableViewFreshTypeUp) {
        self.page++;
    }
    YWWeakSelf(weakSelf);
    [[YWNoticeManager shareManager] requestNoticeListWithPage:self.page pageSize:10 withComplete:^(BOOL success) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            if (success) {
                weakSelf.dataSource = nil;
                [weakSelf.tableView reloadData];
                NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
                [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeNotice];
            }
        });
    }];
}

//-(void)showAttachment:(YWattachment *)attachment{
//    _attachment = attachment;
//    if (_attachment.localName) {
//        QLPreviewController *previewer = [[QLPreviewController alloc] init];
//        [previewer setDataSource:self];
//        [previewer setCurrentPreviewItemIndex:0];
//        [self.navigationController pushViewController:previewer animated:YES];
//    }
//}
//
//-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
//    return 1;
//}
//
//-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
//    NSString *path = [[YWResourceManager shareManager] fileCachePathFromResourcePath:_attachment.localName];
//    NSURL *url = [NSURL fileURLWithPath:path];
//    return url;
//}

- (void)clickRightBarButtonEvent:(id)sender{
    YWNewNoticeTableViewController *newNoticeTableVc = [[YWNewNoticeTableViewController alloc] init];
    [self.navigationController pushViewController:newNoticeTableVc animated:YES];
}

#pragma mark - YWNewNoticeAndTempMissionCellDelegate
-(void)handleExpandButton:(UITableViewCell *)cell{
    NSIndexPath* indexPath = [self.tableView indexPathForCell:(YWNoticeAndTempMissionCell*)cell];
    id object = self.dataSource[indexPath.section][indexPath.row];
    if ([object isKindOfClass:[YWNotice class]]) {
        YWNotice *notice = (YWNotice*)object;
        notice.isExpand = notice.isExpand ? NO : YES;
    }else{
        YWTempMission *tempMission = (YWTempMission*)object;
        tempMission.isExpand = tempMission.isExpand ? NO : YES;
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - Notifications
- (void)setUpNotifications{
    [[YWNotifyManager shareManager] addPushNoticeObserver:self selector:@selector(handlePushNoticeEvent:)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshYWNoticeNotification:) name:KRefreshPostYWNoticeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshYWNoticeNotification:) name:KRefreshDeleteYWNoticeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshYWNoticeNotification:) name:KRefreshModifyYWNoticeNotification object:nil];
}

- (void)refreshYWNoticeNotification:(id)sender{
    _dataSource = nil;
    [self.tableView reloadData];
}

-(void)handlePushNoticeEvent:(NSNotification *)noti{
    if (![noti.object isKindOfClass:[YWPushWorkNotice class]]) {
        return;
    }
    YWPushWorkNotice *workNotice = (YWPushWorkNotice *)noti.object;
    
    //遍历当前数据源，推送的id是否在当前数据源里
    __block BOOL needRequest = YES;
    [self.dataSource enumerateObjectsUsingBlock:^(NSArray*  _Nonnull array, NSUInteger idx, BOOL * _Nonnull arrayStop) {
        [array enumerateObjectsUsingBlock:^(id  _Nonnull object, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([object isKindOfClass:[YWNotice class]]) {
                YWNotice *notice = (YWNotice*)object;
                if (notice.noticeId==workNotice.workNoticeId) {
                    needRequest = NO;
                    *arrayStop = YES;
                    *stop = YES;
                }
            }
        }];
    }];
    
    //网络请求数据
    if (needRequest) {
        YWWeakSelf(weakSelf);
        [[YWNoticeManager shareManager] requestNoticeListWithPage:1 pageSize:10 withComplete:^(BOOL success) {
            if (success) {
                weakSelf.dataSource = nil;
                [weakSelf.tableView reloadData];
            }
        }];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
